//
//  MTUserAccountViewModel.swift
//  MTWeiBo
//
//  Created by user on 2017/7/25.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
//  封装OAuth相关登录接口,提示： 和用户数据相关的操作找HMUserAccountViewModel
class MTUserAccountViewModel: NSObject {

    //单利全局访问点
    static let shardViewModel: MTUserAccountViewModel = MTUserAccountViewModel()
    
    //构造函数私有
    private override init() {
        super.init()
        //  从本地沙盒路径解档用户模型对象
        userAccount = MTUserAccount.loadUserAccount()
    }
    
    //引用模型
    var userAccount: MTUserAccount?
    //是否登录的标记
    var islogin: Bool {
        return accessToken != nil
    }
    
    //获取token
    var accessToken: String? {
        guard let token = userAccount?.access_token else{
            return nil
        }
        //  代码执行到此，token一定有值，判断token是否过期
        let result = userAccount?.expiresDate?.compare(Date())
        if result == ComparisonResult.orderedDescending{
            print(userAccount?.name)
            //表示没过期
            return token
        }
        return nil
    }
    
    //通过code(授权码)获取令牌（accessToken）
    func requestAccessToken(code: String,callBack:@escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            //执行到此说明请求成功
            //转成对应的字典类型
            let dict = response as! [String: Any]
            //字典转模型
            let userAccount = MTUserAccount(dict: dict)
           // print(userAccount.access_token)
            
            //获取用户信息
            self.requestUserInfo(userAccount: userAccount,callBack:callBack )
        }
    }
    
    //获取用户信息
    private func requestUserInfo(userAccount: MTUserAccount,callBack:@escaping (Bool)->()) {
        //令牌
        let token = userAccount.access_token!
        //uid
        let uid = userAccount.uid
        HMNetworkTools.sharedTools.requestUserInfo(access_token: token, uid: uid) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            //执行到此说明请求成功
            //转成对应的字典
            let dict = response as! [String: Any]
            //给对象属性赋值
            userAccount.name = dict["name"] as? String
            userAccount.avatar_large = dict["avatar_large"] as? String
           // print(userAccount.name)
            //登录成功,保存用户对象
            userAccount.saveUserAccount()
            //记录用户模型
            self.userAccount = userAccount
            callBack(true)
        }
        
    }

    
}
